package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;

import tools.SendEmail;
import tools.Tool;
import utils.db.impl.EditAccount;
import utils.db.impl.UserFetcher;

/**
 * Servlet implementation class RemindPasswordServlet
 */
@WebServlet("/RemindPasswordServlet")
public class RemindPasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session;
		String email = request.getParameter("email");
		
		
		if(email!=""){
			UserFetcher u=new UserFetcher();
			if(Tool.checkEmailFormat(email)){
				if(u.checkUserExist(email)){
					String newPassword = Tool.setRandomPassword();
					EditAccount edit = new EditAccount();
					edit.remindPassword(email,DigestUtils.md5Hex(newPassword));
					SendEmail.sendPasswordEmail(email, newPassword);
					session=request.getSession(true);
					session.setAttribute("warning", "Hasło zostało wysłane na podany adres email!");
					response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
					response.setHeader("Location", "index.jsp?page=forgotPassword");
				}else{
					//nie ma takiego uzytkownika
					session=request.getSession(true);
					session.setAttribute("warning", "Nie ma takiego użytkownika w bazie!<a href=index.jsp?page=register#pages> Zarejestruj się.</a>");
					response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
					response.setHeader("Location", "index.jsp?page=forgotPassword");
				}
			}else{
				session=request.getSession(true);
				session.setAttribute("warning", "Błędny format email!");
				response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
				response.setHeader("Location", "index.jsp?page=forgotPassword");
			}
		}else{
			session=request.getSession(true);
			session.setAttribute("warning", "Pole pozostało puste!");
			response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
			response.setHeader("Location", "index.jsp?page=forgotPassword");
		}
	}

}
